package com.lanou.dllo.vc.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.easemob.chat.EMConversation;
import com.easemob.chat.VoiceMessageBody;
import com.lanou.dllo.vc.R;
import com.lanou.dllo.vc.greendao.ChatMessage;
import com.lanou.dllo.vc.util.UserUtils;
import com.lanou.dllo.vc.volley.VolleySingleton;

import java.io.IOException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by dllo on 15/11/24.
 */
public class ChatAdapter extends BaseAdapter {
    private Context context;
    private List<ChatMessage> chatMessages;
    private LayoutInflater inflater;
    private EMConversation conversation;
    private MediaPlayer mediaPlayer;
    private VoiceMessageBody voiceBody;

    public ChatAdapter(Context c) {
        this.context = c;
        inflater = LayoutInflater.from(c);
     //  this.conversation = EMChatManager.getInstance().getConversation(username);
    }

    public void addData(List<ChatMessage> chatMessages) {
        Log.i("lanou", "1---------------" + chatMessages);
        this.chatMessages = chatMessages;
        notifyDataSetChanged();

    }

    @Override
    public int getCount() {
        return chatMessages != null && chatMessages.size() > 0 ? chatMessages.size() : 0;
    }

    @Override
    public ChatMessage getItem(int position) {
        return chatMessages.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.chat_item, parent, false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final ChatMessage chatMessage = chatMessages.get(position);

        int from_type = -1, to_type = -1;
        if (chatMessage.getFromUsre_Con() != null) {
            from_type = getMsgType(chatMessage.getFromUsre_Con().toLowerCase());
        }

        if (chatMessage.getToUsre_Con() != null) {
            to_type = getMsgType(chatMessage.getToUsre_Con());
        }
        Log.i("test", "---->>>" + from_type);


        if (from_type != -1) {//接收消息
            Log.i("lanou", "我不应该进来——————————————————" + chatMessage.getFromUsre_Con());
            String img = chatMessage.getFromUserImg();//头像
            holder.fromChat.setVisibility(View.VISIBLE);
            holder.myChat.setVisibility(View.GONE);
            if (from_type == type_img) {//以http：//开头的为图片网址
                holder.getPicture.setVisibility(View.VISIBLE);
                holder.fromVoiceIv.setVisibility(View.GONE);
                holder.chat_text.setVisibility(View.GONE);
                holder.locationTv.setVisibility(View.GONE);
                getBitmap(chatMessage.getFromUsre_Con(), holder.getPicture);//设置发来的图片
            }
            if (from_type == type_ee) {//表情
                String str_emtion[] = chatMessage.getFromUsre_Con().split("\"");
                holder.getPicture.setVisibility(View.GONE);
                holder.chat_text.setVisibility(View.VISIBLE);
                holder.fromVoiceIv.setVisibility(View.GONE);
                holder.locationTv.setVisibility(View.GONE);
                int resId = context.getResources().getIdentifier(str_emtion[1], "mipmap", context.getPackageName());
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
                ImageSpan imageSpan = new ImageSpan(context, bitmap);
                SpannableString spannableString = new SpannableString(str_emtion[1]);
                spannableString.setSpan(imageSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                if (str_emtion[1] != "delete_expression") {
                    holder.chat_text.setText(spannableString);
                }

            }
            if (from_type == type_voice) {//语音消息
                final String str[] = chatMessage.getFromUsre_Con().split("remoteurl:");
//                if (message != null) {
//                     voiceBody = (VoiceMessageBody) message.getBody();
//                }
                holder.fromVoiceIv.setVisibility(View.VISIBLE);
                holder.chat_text.setVisibility(View.GONE);
                holder.getPicture.setVisibility(View.GONE);
                holder.locationTv.setVisibility(View.GONE);
                holder.fromVoiceIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mediaPlayer = new MediaPlayer();
                        try {
                            mediaPlayer.reset();
                            String url = chatMessage.getFromUsre_Con().substring(chatMessage.getFromUsre_Con().indexOf("localurl:") + "localurl:".length());
                            url = url.substring(0, url.indexOf(","));
                            Log.i("test", "----" + url);
                            mediaPlayer.setDataSource(url);
                            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    mp.start();
                                }
                            });
                            mediaPlayer.prepare();//prepare之后自动播放
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                });

            }

            if (from_type == type_location) {
                String str_location[] = chatMessage.getFromUsre_Con().split(":");
                holder.chat_text.setVisibility(View.GONE);
                holder.fromVoiceIv.setVisibility(View.GONE);
                holder.getPicture.setVisibility(View.GONE);
                holder.locationTv.setVisibility(View.VISIBLE);

                String lo[] = str_location[1].split(",");
                holder.locationTv.setText(lo[0]);
            }

            if (from_type == type_txt) {//文本
                final String str_text[] = chatMessage.getFromUsre_Con().split("\"");
                holder.chat_text.setVisibility(View.VISIBLE);
                holder.getPicture.setVisibility(View.GONE);
                holder.locationTv.setVisibility(View.GONE);
                if (str_text[1] != null) {
                    holder.chat_text.setText(str_text[1]);
                }
                holder.fromVoiceIv.setVisibility(View.GONE);
            }
        } else {//本地发送
            Log.i("lanou", "我发的str[]--------->" + chatMessage.getToUsre_Con());
            holder.myChat.setVisibility(View.VISIBLE);
            holder.fromChat.setVisibility(View.GONE);
            if (chatMessage.getToUsre_Con().endsWith(
                    ".jpg")) {//图片
                Bitmap bitmap = getimage(chatMessage.getToUsre_Con());
                holder.myPicture.setImageBitmap(bitmap);
                holder.myPicture.setVisibility(View.VISIBLE);
                holder.mylocationTv.setVisibility(View.GONE);
                holder.myVoiceIv.setVisibility(View.GONE);
                holder.right_chat_text.setVisibility(View.GONE);
            } else if (chatMessage.getToUsre_Con().startsWith("ee_")) {//表情
                holder.myPicture.setVisibility(View.GONE);
                holder.myVoiceIv.setVisibility(View.GONE);
                holder.right_chat_text.setVisibility(View.VISIBLE);
                holder.chat_text.setVisibility(View.VISIBLE);
                holder.mylocationTv.setVisibility(View.GONE);
                int resId = context.getResources().getIdentifier(chatMessage.getToUsre_Con(), "mipmap", context.getPackageName());
                Bitmap bitmap = null;
                bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
                ImageSpan imageSpan = new ImageSpan(context, bitmap);
                SpannableString spannableString = new SpannableString(chatMessage.getToUsre_Con());
                spannableString.setSpan(imageSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                if (chatMessage.getToUsre_Con() != "delete_expression") {
                    holder.right_chat_text.setText(spannableString);
                }
            } else if (chatMessage.getToUsre_Con().endsWith(".mp3")) {//语音消息
                holder.right_chat_text.setVisibility(View.GONE);
                holder.myVoiceIv.setVisibility(View.VISIBLE);
                holder.myPicture.setVisibility(View.GONE);
                holder.mylocationTv.setVisibility(View.GONE);
                holder.myVoiceIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mediaPlayer = new MediaPlayer();
                        try {
                            mediaPlayer.reset();
                            mediaPlayer.setDataSource(chatMessage.getToUsre_Con());
                            Log.i("lanou", "voiceBody--------" + chatMessage.getToUsre_Con());
                            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    mp.start();
                                }
                            });
                            mediaPlayer.prepare();//prepare之后自动播放
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                });
            } else if (chatMessage.getToUsre_Con().startsWith("location:")) {
                String str_location = chatMessage.getToUsre_Con().substring("location:".length());
                holder.myPicture.setVisibility(View.GONE);
                holder.myVoiceIv.setVisibility(View.GONE);
                holder.right_chat_text.setVisibility(View.GONE);
                holder.mylocationTv.setVisibility(View.VISIBLE);
                holder.mylocationTv.setText(str_location);
            } else {//文本消息
                Log.i("lanou", "文本消息-----------------》》》");
                holder.right_chat_text.setVisibility(View.VISIBLE);
                holder.mylocationTv.setVisibility(View.GONE);
                holder.right_chat_text.setText(chatMessage.getToUsre_Con());
                holder.myPicture.setVisibility(View.GONE);
                holder.myVoiceIv.setVisibility(View.GONE);
            }





          // UserUtils.setCurrentUserAvatar(context, holder.chat_header);


        }
        return convertView;
    }

    public final int type_ee = 0;
    public final int type_txt = 1;
    public final int type_voice = 2;
    public final int type_img = 3;
    public final int type_location = 4;

    private int getMsgType(String msg) {

        if (msg.startsWith("txt")) {
            if (msg.contains("ee_"))
                return type_ee;//表情
            else return type_txt;//文字
        }
        if (msg.startsWith("voice"))
            return type_voice;//语音
        if (msg.startsWith("http://"))
            return type_img;//图片
        if (msg.startsWith("location"))
            return type_location;
        return -1;
    }

    class ViewHolder {
        @Bind(R.id.user_imgIv)
        ImageView chat_header;
        @Bind(R.id.chat_conTv)
        TextView chat_text;
        @Bind(R.id.myChat)
        RelativeLayout myChat;
        @Bind(R.id.fromChat)
        LinearLayout fromChat;
        @Bind(R.id.right_chat_conTv)
        TextView right_chat_text;
        @Bind(R.id.getPictureIv)
        NetworkImageView getPicture;
        @Bind(R.id.myPictureIv)
        ImageView myPicture;
        @Bind(R.id.fromVoiceIv)
        TextView fromVoiceIv;
        @Bind(R.id.myVoiceIv)
        TextView myVoiceIv;
        @Bind(R.id.locationTv)
        TextView locationTv;
        @Bind(R.id.mylocationTv)
        TextView mylocationTv;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    //设置NetworkImage
    private void getBitmap(String url, final NetworkImageView networkImageView) {
        ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();
        networkImageView.setDefaultImageResId(R.mipmap.ic_launcher);
        networkImageView.setErrorImageResId(R.mipmap.ic_launcher);
        networkImageView.setImageUrl(url, imageLoader);
    }

    private Bitmap getimage(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);//此时返回bm为空
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
//        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
        return bitmap;
    }

}
